package edu.csu.smartpark.util;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;


@Component
@Slf4j
public class QRCodeUtil {
    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "jpg";
    private static final int CODE_WIDTH = 400;
    private static final int CODE_HEIGHT = 400;

    /*
    * @Description: 二维码自定义配置函数
    * @Author: LZY
    * @Date: 2021/6/24 15:34
    */
    private static Map<EncodeHintType, Object> getConfig(){
       Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        return hints;
    }

    public static String generateQRCode(String content) {
        StringBuffer qrCode = new StringBuffer();
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, getConfig());
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
            ImageIO.write(image, FORMAT_NAME, os);
            qrCode.append("data:image/png;base64,");
            // 千万不要jdk自带的base64编码，实测是个坑
            qrCode.append(Base64.encodeBase64String(os.toByteArray()));
            return qrCode.toString();
        }catch (Exception e){
            log.warn("generate code error");
            return null;
        }

    }


}
